<template>
  <div class="bfdhbox"></div>
</template>

<script>
import * as THREE from 'three'
// import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js'
export default {
  props: {
    mxmtnumber: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      baseURL: 'https://zfatt.oss-cn-beijing.aliyuncs.com/experiment/zk/',
      loading: true,
      maincontWidth: 0,
      maincontHeight: 0,
      maincontSc: 0,
      camera: null,
      scene: null,
      renderer: null,
      objectReItem: null,
      controls: null,
      newcontrols: null,
      clock: null,
      raycaster: null,
      mouse: null,
      //cameraOriginal: [1, 0.5, 6.876],
      cameraOriginal: [1, 0.5, -0.3],
      objects: [],
      objectFather: null
    }
  },
  created() {},
  mounted() {
    this.init()
  },
  methods: {
    // 使用模体
    mtstart() {
      if (this.mxmtnumber == 'ShuiMo_hao33.glb') {
        this.$emit('mtstart', 1)
      } else {
        this.$emit('mtstart', 2)
      }
    },
    // 返回
    back() {
      this.$emit('back')
    },
    init() {
      this.$nextTick(() => {
        this.maincontWidth = this.$el.offsetWidth
        this.maincontHeight = this.$el.offsetHeight
        this.maincontSc = this.maincontWidth / this.maincontHeight
        this.clock = new THREE.Clock()
        this.mouse = new THREE.Vector2()
        this.raycaster = new THREE.Raycaster()
        this.initScene()
        this.clock = new THREE.Clock()
      })
    },
    initScene() {
      let scene = new THREE.Scene()
      scene.background = null
      this.scene = scene
      this.initLight() //灯光
      this.initCamera() //相机
      this.initRenderer() //加载器
      //   this.initControl()
      this.animate() //刷新场景
      this.initFile() //添加临时盒子
      // this.zx()
      //控制器（不需要可屏蔽）
    },
    initLight() {
      const ambientLight = new THREE.AmbientLight(0xffffff, 1)
      this.scene.add(ambientLight)
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.4)
      directionalLight.position.set(5, 5, 5)
      directionalLight.castShadow = true
      directionalLight.shadow.camera.top = 10
      directionalLight.shadow.camera.bottom = 10
      directionalLight.shadow.camera.left = 10
      directionalLight.shadow.camera.right = -10
      this.scene.add(directionalLight)
    },
    initCamera() {
      let camera = new THREE.PerspectiveCamera(50, this.maincontSc, 0.1, 1000)
      //   camera.position.set(0.9, 1.6, -0.21)
      //   camera.lookAt(0, 0, 0)
      this.camera = camera

      this.scene.add(this.camera)
      //   this.move(
      //     [0.151, 1.689, -7.595],
      //     [-131.12 / 180, 7.39 / 180, 171.62 / 180]
      //   )

      this.move(
        [-1.66, 1.626, -1.779],
        [-157.84 / 180, 0.1 / 180, 179.96 / 180]
      )
    },
    move(position, rotation) {
      // this.controls.enabled = false
      this.camera.position.set(position[0], position[1], position[2])
      this.camera.rotation.set(
        rotation[0] * Math.PI,
        rotation[1] * Math.PI,
        rotation[2] * Math.PI
      )
      this.camera.updateProjectionMatrix()
    },
    initRenderer() {
      let renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true
      })
      renderer.setPixelRatio(window.devicePixelRatio)
      renderer.setSize(this.maincontWidth, this.maincontHeight)
      renderer.shadowMap.enabled = true
      renderer.shadowMap.type = THREE.PCFShadowMap
      renderer.outputEncoding = THREE.sRGBEncoding
      this.renderer = renderer
      this.$el.appendChild(this.renderer.domElement)
      window.addEventListener('resize', this.onWindowResize)
    },
    onWindowResize() {
      this.maincontWidth = this.$el.offsetWidth
      this.maincontHeight = this.$el.offsetHeight
      this.maincontSc = this.maincontWidth / this.maincontHeight
      this.camera.aspect = this.maincontSc
      this.camera.updateProjectionMatrix()
      this.renderer.setSize(this.maincontWidth, this.maincontHeight)
    },
    initFile() {
      let that = this
      let gltf_loader = new GLTFLoader()
      const dracoLoader = new DRACOLoader()
      // dracoLoader.setDecoderPath('/draco/')
      dracoLoader.setDecoderPath(
        'http://zfatt.oss-cn-beijing.aliyuncs.com/threejs/draco/'
      )

      dracoLoader.preload()
      gltf_loader.setDRACOLoader(dracoLoader)
      //加载模型
      gltf_loader.load(this.baseURL + this.mxmtnumber, (glat) => {
        that.loading = false
        let objectReItem = glat.scene
        this.objectFather = glat
        objectReItem.traverse(function (child) {
          if (child.isMesh) {
            child.castShadow = true
            child.receiveShadow = true
            //

            // child.scale.multiplyScalar(1.6, 1.6, 1.6)
          }
        })
        // objectReItem.rotation.y = 1.8
        console.log('获取到动画名称', this.objectFather.animations)
        that.scene.add(objectReItem)
        this.playAction('1', '1.2')
      })
    },
    onDocumentMouseMove(event) {
      event.preventDefault()

      let maincontWidth = this.$el.offsetWidth
      let maincontHeight = this.$el.offsetHeight
      this.mouse.x = (event.offsetX / maincontWidth) * 2 - 1
      this.mouse.y = -(event.offsetY / maincontHeight) * 2 + 1
      this.raycaster.setFromCamera(this.mouse, this.camera)
      const intersections = this.raycaster.intersectObjects(this.objects)
      if (intersections.length > 0) {
        document.body.style.cursor = 'pointer'
      } else {
        document.body.style.cursor = 'initial'
      }
    },
    onDocumentMouseDown(event) {
      event.preventDefault()

      let maincontWidth = this.$el.offsetWidth
      let maincontHeight = this.$el.offsetHeight
      this.mouse.x = (event.offsetX / maincontWidth) * 2 - 1
      this.mouse.y = -(event.offsetY / maincontHeight) * 2 + 1
      this.raycaster.setFromCamera(this.mouse, this.camera)
      //   const intersections = this.raycaster.intersectObjects(this.objects)
      //   if (intersections.length > 0) {
      //     this.$emit('clickItem', intersections[0].object.name)
      //   }
    },

    initControl() {
      this.$el.addEventListener('mousemove', this.onDocumentMouseMove, false)
      this.$el.addEventListener('click', this.onDocumentMouseDown, false)
      //   this.controls = new OrbitControls(this.camera, this.renderer.domElement)
      this.controls.maxDistance = 2
    },
    zx() {
      var offset = null

      offset = new THREE.Vector3(0, 0, 0)
      offset.applyEuler(this.camera.rotation)
      this.controls.target.copy(this.camera.position).sub(offset)
    },
    animate() {
      requestAnimationFrame(this.animate)
      if (this.theMixer) {
        //动画渲染  3000 控制动画没一帧之间的时长
        this.theMixer.update(this.clock.getDelta())
        // this.clock.getDelta()
      }
      this.renderer.render(this.scene, this.camera)
    },
    playAction(animationName, realName) {
      console.log('播放了动画名称', animationName, '点击的物体', realName)
      this.playIng = true
      const theMixer = new THREE.AnimationMixer(this.objectFather.scene) //动画的物体
      const clip = THREE.AnimationClip.findByName(
        this.objectFather.animations,
        animationName
      ) //要播放的动画名称
      const action = theMixer.clipAction(clip)
      console.log('ssss', clip)

      action.loop = THREE.LoopOnce //动画只执行一次
      action.clampWhenFinished = true //播放完成之后自动结束
      action.play()
      this.action = action
      theMixer.addEventListener('finished', () => {
        return setTimeout(() => {
          this.playIng = false
          this.$emit('clickItemwc', realName)
          console.log('动画播放完成')
        }, 600)
      })
      this.theMixer = theMixer
    }
  }
}
</script>
